/**
 * 作者：陈文斌 on 2019/1/5.
 * 邮箱：chen_wennbin@163.com
 * 版本：v1.0
 */

import 'package:flutter/material.dart';
import 'package:crm/model/main_scoped_model.dart';
import 'package:crm/model/ClientManager/client_info_model.dart';
import 'package:crm/component/ClientManager/client_manager_arrangement_row.dart';
import 'package:crm/component/ClientManager/client_manager_arrangement_more_row.dart';
import 'package:crm/view/Refresh/refresh_footer_normal.dart';
import 'package:crm/viewModel/ClientManager/client_manager_view_model.dart';

class ClientManagerList extends StatefulWidget {
  final int clientType;

  @override
  ClientManagerList({Key key, this.clientType}) : super(key: key);

  State<StatefulWidget> createState() => _ClientManagerListState();
}

class _ClientManagerListState extends State<ClientManagerList>
    with AutomaticKeepAliveClientMixin {
  ScrollController _listController = ScrollController();
  List<ClientInfoModel> _clientsInfo = List<ClientInfoModel>();
  bool _isPerformingRequest = false;
  int _page = 0;
  bool _isMore = true;

  _get(page) async {
    if (!_isPerformingRequest) {
      _isPerformingRequest = true;
      ClientManagerVM().getListData(
        page,
        _clientsInfo,
        customerType: widget.clientType,
        callback: (clients, bool isMore) {
          // 请求成功
          _isMore = isMore;
          _isPerformingRequest = false;
          _clientsInfo = clients;

          if (!mounted) return;
          setState(() {});
        },
        errorCallback: (errMsg) => print(errMsg),
      );
    }
  }

  @override
  void initState() {
    super.initState();
    _get(_page);
    _listController.addListener(() {
      if (_listController.position.pixels ==
          _listController.position.maxScrollExtent) _get(++_page);
    });
  }

  @override
  void dispose() {
    super.dispose();
    _listController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final clientManagerScopedModel = MainModel().of(context);
    return RefreshIndicator(
      displacement: 20.0,
      child: createListView(clientManagerScopedModel),
      onRefresh: () async {
        _page = 0;
        _get(_page);
      },
    );
  }

  Widget createListView(MainModel clientManagerScopedModel) {
    return ListView.builder(
      controller: _listController,
      physics: const AlwaysScrollableScrollPhysics(),
      itemCount: _clientsInfo.length + 1,
      itemBuilder: (context, i) {
        if (i < _clientsInfo.length) {
          ClientInfoModel _clientInfo = _clientsInfo[i];
          return clientManagerScopedModel.clientManagerListIsArrangement
              ? ClientManagerArrangementRow(
                  clientInfo: _clientInfo,
                )
              : ClientManagerArrangementMoreRow(
                  clientInfo: _clientInfo,
                );
        } else {
          return RefreshFooterNormal(isMore: _isMore);
        }
      },
    );
  }

  @override
  bool get wantKeepAlive => true;
}
